/**
 * Copyright (c) 2012 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.wordbattle.db;

import java.io.IOException;
import java.util.Iterator;

import android.util.Log;

public class DataBaseLoader implements iDatabaseLoader{
  private final iWordLoader myWordLoader;
  private final iStringDatabase myStringDatabase;
  private final iWordFilter myWordFilter;
  private final int myWordLimit;
  
  public DataBaseLoader( iWordLoader aWordLoader, iWordFilter aWordFilter, iStringDatabase aStringDatabase, int aWordLimit ) {
    super();
    myWordLoader = aWordLoader;
    myStringDatabase = aStringDatabase;
    myWordFilter = aWordFilter;
    myWordLimit = aWordLimit;
  }
  
  public synchronized void loadLanguage(String aLanguage){
    Log.d( DataBaseLoader.class.getName(), "Loading language '" + aLanguage + "'" );
    //we are already loading this language

    if(!isLanguageLoaded(aLanguage)){
      //start loading the language
      //first create the countdown latch so we know that the language is being loaded
      try{
        myStringDatabase.beginInsertingWords(aLanguage);
        Iterator<String> theWordIterator = myWordLoader.getWordsForLanguage(aLanguage);
        int theCounter = 0;
        while(theWordIterator.hasNext() && (theCounter < myWordLimit || myWordLimit == -1)){
          //regular expressions seem to be extremely heavy on android
//          String theWord = theWordIterator.next().toUpperCase().replaceAll("[^\\p{Alpha}]", "");
          String theWord = theWordIterator.next().toUpperCase(  );
          if(myWordFilter.isValidWord( theWord )){
            theCounter++;
            myStringDatabase.insertWord( aLanguage, theWord);
            if(theCounter % 1000 == 0) Log.d(DataBaseLoader.class.getName(), "Words inserted: " + theCounter + " last word " + theWord);
          }
        }
        myStringDatabase.insertingWordsCompleted( aLanguage );
      }catch(IOException e){
        Log.e( DataBaseLoader.class.getName(), "Could not load language '" + aLanguage + "'", e );
      }finally{
        myStringDatabase.endInsertingWords(aLanguage);
      }    
    }
  }
  
  public synchronized boolean isLanguageLoaded(String aLanguage){
   return myStringDatabase.isLanguageLoaded(aLanguage); 
  }
}
